package net.sk.china.front.service.impl.user;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import net.sk.china.common.exception.TalkException;
import net.sk.china.common.model.system.SystemCity;
import net.sk.china.common.model.user.UserAddress;
import net.sk.china.common.request.PageParamRequest;
import net.sk.china.front.dao.user.UserAddressDao;
import net.sk.china.front.request.user.UserAddressRequest;
import net.sk.china.front.service.system.SystemCityService;
import net.sk.china.front.service.user.UserAddressService;
import net.sk.china.front.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * UserAddressServiceImpl 接口
 * +----------------------------------------------------------------------
 * | Talk To [ 聊来改善地区金融服务环境，助力企业发展 ]
 * +----------------------------------------------------------------------
 * | Copyright (c) 2018-2024 聊来All rights reserved.
 * +----------------------------------------------------------------------
 * | Licensed ( <a href="http://www.apache.org/licenses/LICENSE-2.0">apache</a> )
 * +----------------------------------------------------------------------
 * | @Author: 聊来 <18970881148@qq.com>
 * +----------------------------------------------------------------------
 * | DateTime: 2024/6/12 21:38
 * +----------------------------------------------------------------------
 */

@Service
public class UserAddressServiceImpl extends ServiceImpl<UserAddressDao, UserAddress> implements UserAddressService {

    @Resource
    private UserAddressDao dao;

    private final UserService userService;

    private final SystemCityService systemCityService;

    public UserAddressServiceImpl(UserService userService, SystemCityService systemCityService) {
        this.userService = userService;
        this.systemCityService = systemCityService;
    }

    /**
     * 用户地址列表
     * @param page 分页参数
     * @return {@code List<UserAddress>}
     */
    @Override
    public List<UserAddress> getList(PageParamRequest page) {
        Integer uid = userService.getUserId();
        PageHelper.startPage(page.getPage(), page.getLimit());

        LambdaQueryWrapper<UserAddress> query = new LambdaQueryWrapper<>();
        query.select(UserAddress::getId, UserAddress::getRealName, UserAddress::getPhone, UserAddress::getProvince,
                UserAddress::getCity, UserAddress::getDistrict, UserAddress::getDetail, UserAddress::getIsDefault);
        query.eq(UserAddress::getUid, uid).eq(UserAddress::getIsDel, false).orderByDesc(UserAddress::getIsDefault).orderByDesc(UserAddress::getId);

        return dao.selectList(query);
    }

    /**
     * 添加地址
     * @param request 地址请求参数
     * @return {@code UserAddress}
     */
    @Override
    public UserAddress create(UserAddressRequest request) {
        UserAddress userAddress = new UserAddress();
        BeanUtils.copyProperties(request, userAddress);
        userAddress.setCity(request.getAddress().getCity());
        userAddress.setCityId(request.getAddress().getCityId());
        userAddress.setDistrict(request.getAddress().getDistrict());
        userAddress.setProvince(request.getAddress().getProvince());

//        SystemCity currentCity = systemCityService.getCityByCityName(request.getAddress().getDistrict());
//        if (ObjectUtil.isNull(currentCity)) {
//            throw new TalkException("当前城市未找到");
//        }
//        userAddress.setCityId(currentCity.getCityId());


        userAddress.setUid(userService.getUserId());
        if (userAddress.getIsDefault()) {
            //把当前用户其他默认地址取消
            cancelDefault(userAddress.getUid());
        }
        saveOrUpdate(userAddress);
        return userAddress;
    }

    /**
     * 删除用户地址
     * @param id 地址id
     * @return {@code boolean}
     */
    @Override
    public boolean delete(Integer id) {
        if (ObjectUtil.isNull(id)) {
            throw new TalkException("地址ID必传");
        }
        LambdaQueryWrapper<UserAddress> query= new LambdaQueryWrapper<>();
        query.eq(UserAddress::getId, id).eq(UserAddress::getUid, userService.getUserId());

        return dao.delete(query) >= 1;
    }

    /**
     * 获取地址详情
     * @param id 地址id
     * @return {@code UserAddress}
     */
    @Override
    public UserAddress getDetail(Integer id) {
        if (ObjectUtil.isNull(id)) {
            throw new TalkException("地址ID必传");
        }
        Integer userId = userService.getUserId();
        LambdaQueryWrapper<UserAddress> query = new LambdaQueryWrapper<>();
        query.select(UserAddress::getId, UserAddress::getRealName, UserAddress::getPhone, UserAddress::getProvince,
                UserAddress::getCity, UserAddress::getDistrict, UserAddress::getDetail, UserAddress::getIsDefault);
        query.eq(UserAddress::getId, id).eq(UserAddress::getUid, userId).eq(UserAddress::getIsDel, false);

        return dao.selectOne(query);
    }

    /**
     * 获取默认地址
     * @return {@code UserAddress}
     */
    @Override
    public UserAddress getDefaultByUid(Integer uid) {
        LambdaQueryWrapper<UserAddress> query = new LambdaQueryWrapper<>();
        query.eq(UserAddress::getIsDefault, true).eq(UserAddress::getUid, uid);
        query.last("limit 1");

        return dao.selectOne(query);
    }

    /**
     * 获取默认地址
     * @return {@code UserAddress}
     */
    @Override
    public UserAddress getDefault() {
        LambdaQueryWrapper<UserAddress> query = new LambdaQueryWrapper<>();
        query.eq(UserAddress::getIsDefault, true).eq(UserAddress::getUid, userService.getUserId());
        query.last("limit 1");

        return dao.selectOne(query);
    }

    /**
     * 设置默认地址
     * @param id 地址id
     * @return {@code boolean}
     */
    @Override
    public boolean setDefault(Integer id) {
        Integer uid = userService.getUserId();
        // 把当前用户其他默认地址取消
        cancelDefault(uid);

        UpdateWrapper<UserAddress> query = new UpdateWrapper<>();
        query.eq("id", id);
        query.set("is_default", 1);

        return dao.update(null, query) >= 1;
    }

    /**
     * 取消默认地址
     * @param uid 用户ID
     */
    private void cancelDefault(Integer uid) {
        UpdateWrapper<UserAddress> query = new UpdateWrapper<>();
        query.eq("uid", uid);
        query.set("is_default", 0);

        dao.update(null, query);
    }
}
